package com.platform.server.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpRequest;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.paltform.server.entity.ExceIRecomUser;
import com.paltform.server.entity.ExcelService;
import com.paltform.server.entity.ExcelUserInfo;
import com.paltform.server.entity.SysUser;
import com.platform.server.dao.UserDao;
import com.platform.server.dao.WithdrawDao;
import com.platform.server.service.UserService;
import com.platform.server.util.DateTools;
import com.platform.server.util.ExportExcel;
import com.platform.server.util.StringTools;

@Controller
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private WithdrawDao withdrawDao;
	
	@Autowired
	private UserDao userDao;
	
	/**
	 * 用户列表
	 * @return
	 */
	@RequestMapping("/selectUserList")
	public Object selectUserList(HttpServletRequest request,String userid,String startTime,String endTime,String username,String mobile,String entuserid,String oneuserid
			,String grade,String age,String tuimobile,String isEnprise,String isUser){
		SimpleDateFormat fdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String, Object>> lists = userService.selectUserList(userid,startTime, endTime, username, mobile,grade,age,tuimobile,isEnprise,isUser);
		for(int i = 0;i < lists.size();i++){
			lists.get(i).put("create_time",fdt.format(lists.get(i).get("create_time")));
			if(lists.get(i).get("login_time") != null){
				lists.get(i).put("login_time",fdt.format(lists.get(i).get("login_time")));   
			}
		}
		if(!StringTools.isEmpty(userid)){
			if(!StringTools.isEmpty(entuserid)){
				request.setAttribute("entuserid", entuserid);
			}
			if(!StringTools.isEmpty(oneuserid)){
				request.setAttribute("oneuserid", oneuserid);
			}
			request.setAttribute("lists", lists);
			return "/ui/admin/user_details.jsp";
		}
		request.setAttribute("lists", lists);
		request.setAttribute("nums", lists.size());
		return "/ui/admin/user_list.jsp";
	}
	
	/**
	 * 对用户进行封号或解封
	 */
	@RequestMapping("/updateUserStatu")
	public Object updateUserStatu(HttpSession session,String params){
		String[] split = params.split(",");
		String username = null;
		if(split.length == 2){
			username = "";
		}else{
			username = split[2];
		}
		userService.updateUserStatu(Integer.parseInt(split[0]), split[1]);
		//增加日志操作记录
		SysUser su = (SysUser) session.getAttribute("user");
		String user = null,content = null;
		if(su != null){
			user = su.getSys_name();
		}
		if("0".equals(split[1])){
			content = "对" + username + "进行了封号操作";
		}else if("1".equals(split[1])){
			content = "对" + username + "进行了解封 操作";
		}
		withdrawDao.insertLog(user, content);
		if(split.length==4){
			return "/selectUserCompanyList";
		}else if(split.length==5){
			return "/selectUserCompanyList?userid="+split[split.length-1];
		}else{
			return "/selectUserList";
		}
	}
	
	/**
	 * 查看用户的推荐人列表
	 */
	@RequestMapping("/selectRecommendList")
	public Object selectRecommendList(HttpServletRequest request,HttpSession session,String phone,String startTime,String endTime,
			String username,String mobile,String test){
		SimpleDateFormat fdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(!StringTools.isEmpty(test)){
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> arrayList = (List<Map<String, Object>>) session.getAttribute("arrayList");
			List<Map<String,Object>> lists = new ArrayList<>();
			for(int i = 0;i < arrayList.size();i++){
				Date create_time = (Date)arrayList.get(i).get("create_time");
				long time = create_time.getTime();
				String user = arrayList.get(i).get("username") + "";
				String mb = (String) arrayList.get(i).get("mobile") + "";
				if((StringTools.isEmpty(startTime) || StringTools.isEmpty(endTime)) && StringTools.isEmpty(username) && StringTools.isEmpty(mobile)){
					lists.add(arrayList.get(i));continue;
				}
				if(!StringTools.isEmpty(startTime) && !StringTools.isEmpty(endTime) && StringTools.isEmpty(username) && StringTools.isEmpty(mobile)){
					Date stime = DateTools.str2Date(startTime, "yyyy-MM-dd");
					Date etime = DateTools.str2Date(endTime, "yyyy-MM-dd");
					long starttime = stime.getTime();
					long endtime = etime.getTime();
					if(starttime < time && time < endtime){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(!StringTools.isEmpty(startTime) && !StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && StringTools.isEmpty(mobile)){
					Date stime = DateTools.str2Date(startTime, "yyyy-MM-dd");
					Date etime = DateTools.str2Date(endTime, "yyyy-MM-dd");
					long starttime = stime.getTime();
					long endtime = etime.getTime();
					if(starttime < time && time < endtime && user.indexOf(username) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(!StringTools.isEmpty(startTime) && !StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && !StringTools.isEmpty(mobile)){
					Date stime = DateTools.str2Date(startTime, "yyyy-MM-dd");
					Date etime = DateTools.str2Date(endTime, "yyyy-MM-dd");
					long starttime = stime.getTime();
					long endtime = etime.getTime();
					if(starttime < time && time < endtime && user.indexOf(username) != -1 && mb.indexOf(mobile) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(StringTools.isEmpty(startTime) && StringTools.isEmpty(endTime) && StringTools.isEmpty(username) && !StringTools.isEmpty(mobile)){
					if(mb.indexOf(mobile) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(StringTools.isEmpty(startTime) && StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && !StringTools.isEmpty(mobile)){
					if(user.indexOf(username) != -1 && mb.indexOf(mobile) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(!StringTools.isEmpty(startTime) && !StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && !StringTools.isEmpty(mobile)){
					Date stime = DateTools.str2Date(startTime, "yyyy-MM-dd");
					Date etime = DateTools.str2Date(endTime, "yyyy-MM-dd");
					long starttime = stime.getTime();
					long endtime = etime.getTime();
					if(starttime < time && time < endtime && user.indexOf(username) != -1 && mb.indexOf(mobile) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(StringTools.isEmpty(startTime) && StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && StringTools.isEmpty(mobile)){
					if(user.indexOf(username) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(StringTools.isEmpty(startTime) && StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && !StringTools.isEmpty(mobile)){
					if(user.indexOf(username) != -1  && mb.indexOf(mobile) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
				if(!StringTools.isEmpty(startTime) && !StringTools.isEmpty(endTime) && !StringTools.isEmpty(username) && !StringTools.isEmpty(mobile)){
					Date stime = DateTools.str2Date(startTime, "yyyy-MM-dd");
					Date etime = DateTools.str2Date(endTime, "yyyy-MM-dd");
					long starttime = stime.getTime();
					long endtime = etime.getTime();
					if(starttime < time && time < endtime && user.indexOf(username) != -1 && mb.indexOf(mobile) != -1){
						lists.add(arrayList.get(i));
						continue;
					}else{
						continue;
						
					}
				}
			}
			request.setAttribute("lists", lists);
			request.setAttribute("nums", lists.size());
			return "/ui/admin/recommend_user_list.jsp";
		}
		List<Map<String,Object>> lists = new ArrayList<>();
		String[] recommendid = userService.selectRecommendList(phone);
		for(int i = 0;i < recommendid.length;i++){
			List<Map<String, Object>> arrayList = userService.selectUserList(recommendid[i],null,null,null,null,null,null, null, null, null);
			if(arrayList.size() > 0){
				if(arrayList.get(0).get("login_time") != null){
					arrayList.get(0).put("login_time",fdt.format(arrayList.get(0).get("login_time")));   
				}
				lists.add(arrayList.get(0));
			}
		}
		request.setAttribute("lists", lists);
		request.setAttribute("nums", lists.size());
		request.setAttribute("phone", phone);
		session.setAttribute("arrayList", lists);
		return "/ui/admin/recommend_user_list.jsp";
	}
	/**
	 * 下级用户列表
	 */
	@RequestMapping("/selectOneUserList")
	public Object selectOneUserList(HttpServletRequest request,HttpSession session,String userid,String startTime,String endTime,
			String username,String mobile,String address, String level){
		List<Map<String,Object>> lists = userService.selectOneUserList(userid, startTime, endTime, username, address, mobile,level);
		for (Map<String, Object> map : lists) {
			if(map.get("expire_time")!=null){
			    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			    try {
					Date dt1 = df.parse(map.get("expire_time").toString());
					if(dt1.getTime()>=new Date().getTime()){
						map.put("expire_time", "1");
						}else{
							map.put("expire_time", "0");
						}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
				continue;
				}
			}
		}
		request.setAttribute("lists", lists);
		request.setAttribute("userid", userid);
		request.setAttribute("nums", lists.size());
	return "/ui/admin/one_user_list.jsp";
	}
	/**
	 * 用户服务列表
	 */
	@RequestMapping("/selectUserOrderList")
	public Object selectUserOrderList(HttpServletRequest request,HttpSession session,String startTime, String endTime, String order_id,
			String server_type, String mobile, String user_id){
		List<Map<String,Object>> lists = userService.selectUserOrderList(startTime, endTime, order_id, server_type, mobile,user_id);
		Double tc=0.0;
		for (Map<String, Object> map : lists) {
			if(map.get("money")!=null&&!map.get("money").toString().equals("")){
				tc+=Double.parseDouble(map.get("money").toString());
			}
		}
		request.setAttribute("lists", lists);
		request.setAttribute("user_id", user_id);
		request.setAttribute("tc", tc);
		request.setAttribute("nums", lists.size());
	return "/ui/admin/service_list.jsp";
	}
	/**
	 * 查看积分
	 */
	@RequestMapping("/selectIntegral")
	public Object selectIntegral(HttpServletRequest request){
		List<Map<String,Object>> lists = userService.selectIntegral();
		request.setAttribute("lists", lists);
		return "/ui/admin/integral_set.jsp";
	}
	
	/**
	 * 修改积分设置
	 */
	@RequestMapping("/integralSet")
	public void integralSet(HttpSession session,HttpServletResponse response,String common_vip,String copper_vip,String silver_vip,String gold_vip,String five_star,
			String tow_star,String server,String Integral_arrival,String recommend_integral,String vip_server_discount) throws Exception{
		int flag = userService.integralSet(common_vip, copper_vip, silver_vip, gold_vip, five_star,tow_star, server, Integral_arrival, recommend_integral, vip_server_discount);
		SysUser su = (SysUser) session.getAttribute("user");
		String user = null;
		if(su != null){
			user = su.getSys_name();
		}
		withdrawDao.insertLog(user, "修改了积分设置");
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("flag", flag);
        response.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
	}
	
	/**
	 * 删除用户（测试使用）
	 */
	@RequestMapping("/deleteUser")
	public Object deleteUser(String idd){
		@SuppressWarnings("unused")
		int flag  = userDao.deleteUser(idd);
		System.out.println(idd);
		return "/selectUserList";
	}

	// 导出报表
		@RequestMapping("/exportExcel")
		public void exportExcelInInvoice(HttpServletRequest request,HttpServletResponse response){
			//SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<Object> list2 = new ArrayList<Object>();
			List<Map<String, Object>> list = userService.selectUserList(null,request.getParameter("startTime"), request.getParameter("endTime"),request.getParameter("username"),request.getParameter("mobile"),request.getParameter("grade"),request.getParameter("age"),request.getParameter("mobile"), request.getParameter("isEnprise"), request.getParameter("isUser"));
			for(Map<String, Object> user:list){
				ExcelUserInfo userInfo = new ExcelUserInfo();
				userInfo.setUsername(user.get("username"));
				userInfo.setWxName(user.get("wx_name"));
				userInfo.setJobName(user.get("job"));
				userInfo.setZbfAccount(user.get("zfb_account"));
				userInfo.setBankAccount(user.get("bank"));
				
				userInfo.setBankNamet(user.get("bank_name"));
				
				userInfo.setMobile(user.get("mobile"));
				
				userInfo.setRealName(user.get("real_name"));
				userInfo.setIdentityCard(user.get("identity_card"));
				
				if(user.get("gender").equals("1")){
					userInfo.setGender("男");
				}else if(user.get("gender").equals("2")){
					userInfo.setGender("女");
				}else{
					userInfo.setGender("未知");
				}
				userInfo.setAge(user.get("age"));
				userInfo.setLevel(user.get("integral_rank"));
				userInfo.setAuthentication(user.get("integral_rank").equals("1")? "已认证" : "未认证");
				userInfo.setEnterprise(user.get("enterprise_audit").equals("1")? "已认证" : "未认证");
				if(user.get("vip")==null){
					userInfo.setVip( "普通用户");
				}
				if(user.get("vip")!=null&&user.get("vip").equals("1")){
					userInfo.setVip( "VIP1");
				}
				if(user.get("vip")!=null&&user.get("vip").equals("2")){
					userInfo.setVip( "企业VIP");
				}
				if(user.get("vip")!=null&&user.get("vip").equals("3")){
					userInfo.setVip( "VIP2");
				}
				userInfo.setVipStarttime(user.get("vip_start"));
				userInfo.setVipEndtime(user.get("vip_end"));
				userInfo.setReferrerNum(user.get("recommend_nums") == null? "0人" : user.get("recommend_nums"));
				userInfo.setReferrerName(user.get("recommend_mobile"));
				userInfo.setLoginTime(user.get("login_time"));
				list2.add(userInfo);
			}
			String[] titles = {"昵称" , "微信号" , "职称" , "支付宝" , "银行卡" , "开户行" , "手机号" , "姓名" , "身份证" , "性别" ,"年龄" , "用户等级" , "实名认证" , "企业认证" , "会员" , "会员开始时间" , "会员结束时间" , "我推荐的人" , "我的推荐人" , "最近登录时间"};
			ExportExcel.exportExcel("用户信息表.xls", titles, list2, response);
		}
		
		// 导出报表
		@RequestMapping("/exportExcels")
		public void exportExcelInInvoice1(HttpServletResponse response, String phone){
			SimpleDateFormat fdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<Object> list2 = new ArrayList<Object>();
			List<Map<String,Object>> lists = new ArrayList<>();
			String[] recommendid = userService.selectRecommendList(phone);
			for(int i = 0;i < recommendid.length;i++){
				List<Map<String, Object>> arrayList = userService.selectUserList(recommendid[i],null, null, null, null,null,null,null,null,null);
				if(arrayList.size() > 0){
					if(arrayList.get(0).get("login_time") != null){
						arrayList.get(0).put("login_time",fdt.format(arrayList.get(0).get("login_time")));   
					}
					lists.add(arrayList.get(0));
				}
			}
			for(Map<String, Object> user:lists){
				ExceIRecomUser recomUser = new ExceIRecomUser();
				recomUser.setUsername(user.get("username"));
				recomUser.setMobile(user.get("mobile"));
				if(user.get("gender").equals("1")){
					recomUser.setGender("男");
				}else if(user.get("gender").equals("2")){
					recomUser.setGender("女");
				}else{
					recomUser.setGender("未知");
				}
				recomUser.setAddress(user.get("address"));
				recomUser.setLevel(user.get("integral_rank"));
				recomUser.setAuthentication(user.get("integral_rank").equals("1")? "已认证" : "未认证");
				recomUser.setEnterprise(user.get("enterprise_audit").equals("1")? "已认证" : "未认证");
				recomUser.setVip(user.get("vip").equals("1")?"VIP" : "普通用户");
				recomUser.setReferrerNum(user.get("recommend_nums") == null? "0人" : user.get("recommend_nums"));
				recomUser.setLoginTime(user.get("login_time"));
				list2.add(recomUser);
			}
			String[] titles = {"昵称" , "手机号" , "性别" , "地址" , "用户等级" ,  "实名认证" , "企业认证" , "会员" , "我推荐的人" , "最近登录时间"};
			ExportExcel.exportExcel("推荐用户表.xls", titles, list2, response);
		}
		
		// 导出报表
					@RequestMapping("/serverExportExcel")
					public void orderExportExcel(String user_id,String startTime,String endTime,String server_type,String order_id,String mobile,HttpServletResponse response){
						List<Object> list2 = new ArrayList<Object>();
						List<Map<String, Object>> lists = userService.selectUserOrderList(startTime, endTime, order_id, server_type, mobile,user_id);
						for(int i = 0;i < lists.size();i++){
							ExcelService order = new ExcelService();
							order.setOrderId(lists.get(i).get("order_id"));
							order.setUsername(lists.get(i).get("username"));
							order.setMobile(lists.get(i).get("mobile"));
							if(lists.get(i).get("entAudit")==null&&lists.get(i).get("audit").equals("1")){
								order.setEnterprise("个人");
							}else{
								order.setEnterprise("企业");
							}
							order.setRealityPrice(lists.get(i).get("reality_price"));
							order.setServerSubType(lists.get(i).get("server_sub_type"));
							order.setServerType(lists.get(i).get("server_type"));
							order.setRoyaltyPrice(lists.get(i).get("money"));
							list2.add(order);
						}
						String[] titles = {"订单编号" , "用户昵称" , "手机号", "用户类型" , "服务类型" , "服务子类型" ,  "订单金额" ,  "提成金额" };
						ExportExcel.exportExcel("服务列表.xls", titles, list2, response);
					}
}
